package gu;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
public class HttpManager4Form extends HttpManager {
	private List<String> cookies;
	private HttpURLConnection conn;
 
	public void Login(String url, String LoginInfo, String formName) {
		CookieHandler.setDefault(new CookieManager());
		
 		try {
 			String page = GetPageContent(url);
 			String postParams = getFormParams(page, LoginInfo, formName);
 			sendPost(url, postParams);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void sendPost(String url, String postParams) throws Exception {
 		conn = get_connection( new URL(url), "POST" );
		
		if (this.cookies!=null)
			for (String cookie : this.cookies) {
				conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
			}
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
		conn.setDoOutput(true);
		conn.setDoInput(true);
	 
		// Send post request
		DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
		wr.writeBytes(postParams);
		wr.flush();
		wr.close();
	 
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String inputLine;
		StringBuffer response = new StringBuffer();
	 
		while ((inputLine = in.readLine()) != null) {
			response.append(inputLine);
		}
		in.close();
	}
 
	public String GetPageContent(String url){
		responseTime = 0;		// elapse time
		long startTime = System.currentTimeMillis();
		StringBuffer response = new StringBuffer();
		
 		try {
			conn = get_connection(new URL(url), "GET");
			
			if (cookies != null) {
				for (String cookie : this.cookies) {
					conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
				}
			}
			responseCode = conn.getResponseCode();
			if (conn.getResponseCode() != 200) return null;
		 
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String inputLine;
		 
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
		 
			// Get the response cookies
			setCookies(conn.getHeaderFields().get("Set-Cookie"));
			responseTime = System.currentTimeMillis() - startTime;		// elapse time
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
 		
		return response.toString();
	}
	
	public Document GetDocument(String url){
		String html = GetPageContent(url);
		if (html==null) return null;
		return Jsoup.parse(html);
	}
	
	public String getFormParams(String html, String LoginInfo, String formName) throws UnsupportedEncodingException {
		HashMap<String , String> paramMap = new HashMap<String , String>();
		String[] logarr = LoginInfo.split(",");
		for (int i=0; i<logarr.length; i+=2)
			paramMap.put(logarr[i].trim(), logarr[i+1].trim());
			
		Document doc = Jsoup.parse(html);
	 
		Element loginform = doc.getElementById(formName);
		if (loginform==null) {
			Elements forms = doc.getElementsByTag("form");
			loginform = forms.get(0);
		}
		Elements inputElements = loginform.getElementsByTag("input");
		
		String ret = "";
		for (Element inputElement : inputElements) {
			String key = inputElement.attr("name");
			String value = inputElement.attr("value");
			
			String a = paramMap.get(key);
			if (a!=null) value=a;
		  				
			if (!"".equals(ret)) ret += "&";
			ret += key + "=" + URLEncoder.encode(value, "UTF-8");
		}
	 
		return ret;
	}
  
	public HttpURLConnection get_connection(URL url, String reqMethod) throws IOException {
		HttpURLConnection conn;
		if (url.getProtocol().toUpperCase().equals("HTTPS"))
			 conn = (HttpsURLConnection) url.openConnection();
		else conn = (HttpURLConnection ) url.openConnection(); 
	 	 
		conn.setUseCaches(false);
		conn.setRequestMethod(reqMethod);// get, POST
		conn.setRequestProperty("User-Agent", "Mozilla/5.0");
		conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
	 	
		return conn;
	}
  
	public List<String> getCookies() {
		return cookies;
	}
 
	public void setCookies(List<String> cookies) {
		this.cookies = cookies;
	}
}
